const glob = require('glob');
const { chain, each, set } = require('lodash');
const cdnDependencies = require('./config/cdn');

const resolve = (dir) => require('path').join(__dirname, dir);

const publicPath = process.env.VUE_APP_PUBLIC_PATH || '/';

function getEntry(globPath) {
  const pages = {};
  glob.sync(`${globPath}/main.js`).forEach(function(entry, index) {
    let currentEntryPath = entry.split('/').splice(-3);
    pages[index === 0 ? 'index' : currentEntryPath[1]] = {
      entry,
      template: 'src/template/index.html',
      filename: 'index.html',
      chunks: ['chunk-vendors', 'chunk-common', 'index'],
    };
  });
  return pages;
}

const externals = {};
cdnDependencies.forEach((pkg) => {
  externals[pkg.name] = pkg.library;
});

// 引入文件的 cdn 链接
const cdn = {
  css: cdnDependencies.map((e) => e.css).filter((e) => e),
  js: cdnDependencies.map((e) => e.js).filter((e) => e),
};

const isProd = process.env.NODE_ENV === 'production';
const isDev = process.env.NODE_ENV === 'development';
const pages = getEntry('./src/pages/**');

module.exports = {
  pages,
  publicPath,
  lintOnSave: true,
  productionSourceMap: false,
  devServer: {
    publicPath,
    disableHostCheck: !isProd,
  },
  configureWebpack: () => {
    const configNew = {};
    if (isProd) {
      configNew.externals = externals;
    }
    return configNew;
  },
  chainWebpack: (config) => {
    config.plugins.delete('preload');
    config.plugins.delete('prefetch');

    const htmlPluginNames = chain(pages)
      .keys()
      .map((page) => 'html-' + page)
      .value();

    const targetHtmlPluginNames = htmlPluginNames.length
      ? htmlPluginNames
      : ['html'];

    each(targetHtmlPluginNames, (name) => {
      config.plugin(name).tap((options) => {
        set(
          options,
          '[0].cdn',
          process.env.NODE_ENV === 'production' ? cdn : []
        );
        return options;
      });
    });

    config.when(isDev, (config) => config.devtool('cheap-source-map'));

    config.resolve.symlinks(true);

    config.module
      .rule('svg')
      .exclude.add(resolve('src/assets/svg-icons'))
      .end();

    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/assets/svg-icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]',
      })
      .end();

    config.resolve.alias.set('@api', resolve('src/api'));
  },
};
